//
//  AVAduioSessionViewController.swift
//  iOSCases
//
//  Created by 申铭 on 2025/1/11.
//

import UIKit
import AVFAudio
import AVKit

class AVAduioSessionViewController: UIViewController, NibProtocol {
    
    private var player: AVAudioPlayer?

    override func viewDidLoad() {
        super.viewDidLoad()
        
    }

    @IBAction func playMusic(_ sender: Any) {
        guard let pathStr = Bundle.main.path(forResource: "ringtone-caller", ofType: "mp3") else { return }
        
        try? player = AVAudioPlayer(contentsOf: URL(fileURLWithPath: pathStr))
        
        if player?.isPlaying ?? false { return }
        
        player?.prepareToPlay()
        player?.numberOfLoops = -1
        player?.play()
    }
    
    @IBAction func switchReceiver(_ sender: Any) {
        do {
            try AVAudioSession.sharedInstance().setCategory(.playAndRecord, options: [.allowBluetooth, .allowBluetoothA2DP])
        } catch {
            print("切换听筒失败:\(error)")
        }
    }
    
    @IBAction func switchSpeaker(_ sender: Any) {
        do {
            try AVAudioSession.sharedInstance().setCategory(.playAndRecord, options: [.defaultToSpeaker, .allowBluetooth, .allowBluetoothA2DP])
        } catch {
            print("切换扬声器失败:\(error)")
        }
    }
    
    @IBAction func showPickerView(_ sender: Any) {
        let buttonView  = UIView(frame: CGRect(x: -100, y: -100, width: 1, height: 1))
        let routerPickerView =  AVRoutePickerView(frame: buttonView.bounds)
        buttonView.addSubview(routerPickerView)
        
        /// 自动跳转控制中心页面
        for view in routerPickerView.subviews {
            if view.isKind(of: UIButton.self) {
                (view as! UIButton).sendActions(for: .touchUpInside)
            }
        }
    }
}

